﻿using LPP.Core.Services;
using LPP.Entity.Statistic;
using LPP.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;


namespace LPP.Service.BusServices
{
    public class StatisticService : IStatisticService
    {
        private readonly SqlDbContext _context;

        public StatisticService(SqlDbContext context)
        {
            _context = context;
        }

        public async Task<Statistic> GetStatisticAsync(string key)
        {
            return await _context.Statistics.FirstOrDefaultAsync(s => s.Key == key);
        }

        public async Task UpdateStatisticAsync(string key, int value)
        {
            var statistic = await _context.Statistics.FirstOrDefaultAsync(s => s.Key == key);
            if (statistic != null)
            {
                statistic.Value = value;
                statistic.LastUpdated = DateTime.UtcNow;
                _context.Statistics.Update(statistic);
            }
            else
            {
                statistic = new Statistic
                {
                    Key = key,
                    Value = value,
                    LastUpdated = DateTime.UtcNow
                };
                await _context.Statistics.AddAsync(statistic);
            }
            await _context.SaveChangesAsync();
        }

        public async Task<List<Statistic>> GetAllStatisticsAsync()
        {
            return await _context.Statistics.ToListAsync();
        }
    }
}
